var trendlineData = new Array();
var trendlineDate = new Array();
var chartId = 0;
var timer;
function svgGen(posX, posY, value, total, R) {
    var center;
    posX += R;
    posY += R;
    var alpha = 360 / total * value,
            a = (90 - alpha) * Math.PI / 180,
            x = posX + R * Math.cos(a),
            y = posY - R * Math.sin(a),
            path;
    if (total == value) {
        path = "M " + posX + ", " + posY + " m " + -R + ", 0 a " + R + "," + R +
                " 0 1,0 " + (2 * R) + ",0 a " + R + "," + R + " 0 1,0 -" + (2 * R) + ",0";
    } else {
        if (alpha > 180) {
            center = 1;
        } else {
            center = 0;
        }
        path = "M" + posX + "," + (posY - R) + " A" + R + "," + R + "," + 0 +
                "," + center + "," + 1 + "," + x + "," + y;
    }
    return path;
}

function socialGraph(element, posX, posY, strokeColor, radius, percent) {
    var paper = Raphael(element, radius * 2 + 4, radius * 2 + 4);
    var c = paper.path(svgGen(3 + posX, 3 + posY, 100, 100, radius - 3))
            .attr({stroke: "#e5e5e5", opacity: 1, "stroke-width": 6});
    var d = paper.path(svgGen(3 + posX, 3 + posY, percent, 100, radius - 3))
            .attr({stroke: strokeColor, opacity: 1, "stroke-width": 6});
}

var colors = new Array();
colors[2] = "#4f81bd";
colors[1] = "#9bbb59";
colors[0] = "#c0504d";
$(document).ready(function() {
    Raphael.fn.sentiment = function(cx, cy, r, values, labels, stroke) {
        var paper = this,
                rad = Math.PI / 180,
                chart = this.set();
        function sector(cx, cy, r, startAngle, endAngle, params) {
            var x1 = cx + r * Math.cos(-startAngle * rad),
                    x2 = cx + r * Math.cos(-endAngle * rad),
                    y1 = cy + r * Math.sin(-startAngle * rad),
                    y2 = cy + r * Math.sin(-endAngle * rad);
            return paper.path(["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2, "z"]).attr(params);
        }
        var angle = 0,
                total = 0,
                start = 0,
                process = function(j) {
                    var value = values[j],
                            angleplus = 180 * value / total,
                            popangle = angle + (angleplus / 2),
                            color = colors[j],
                            //color = Raphael.hsb(start, .75, 1),
                            ms = 500,
                            delta = 30,
                            //bcolor = Raphael.hsb(start, 1, 1),
                            bcolor = colors[j],
                            p = sector(cx, cy, r, angle, 180, {fill: "90-" + bcolor + "-" + color, stroke: false, "stroke-width": 0}),
                    txt = paper.text(cx + (r + delta + 55) * Math.cos(-popangle * rad), cy + (r + delta + 25) * Math.sin(-popangle * rad), labels[j]).attr({fill: bcolor, stroke: "none", opacity: 0, "font-size": 20});
                    angle += angleplus;
                    chart.push(p);
                    chart.push(txt);
                    start += .1;
                };
        for (var i = 0, ii = values.length; i < ii; i++) {
            total += values[i];
        }
        for (i = 0; i < ii; i++) {
            process(i);
        }
        return chart;
    };
});
var percent = 0;
function increasePercent() {
    percent += 1;
    if ($('#graph0').attr('percent') > percent)
        $('#graph0').find('path').last().attr('d', svgGen(5, 5, percent, 100, 45));
    if ($('#graph1').attr('percent') > percent)
        $('#graph1').find('path').last().attr('d', svgGen(5, 5, percent, 100, 45));
    if ($('#graph2').attr('percent') > percent)
        $('#graph2').find('path').last().attr('d', svgGen(5, 5, percent, 100, 45));
    if ($('#graph3').attr('percent') > percent)
        $('#graph3').find('path').last().attr('d', svgGen(5, 5, percent, 100, 45));
    if (percent == 100)
        clearInterval(inte);
}

function loadTrendLine() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    var filter = {};
    filter.streamId = streamId;
    filter.dateFrom = dateFrom;
    filter.dateTo = dateTo;
    filter.language = language.split(',');
    filter.tags = tag.split(',');
    filter.sentiment = sentiment;
    filter.type = type.split(',');
    filter.source = source.split(',');
    curRequests.push($.get('/ws/trendline/' + streamId + '/' + JSON.stringify(filter), function(r) {
        trendLoadCompleted(JSON.parse(r));
    }));
}

function trendLoadCompleted(r) {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    if (r) {
        total = r.total;
        totalThreads = total.split(';')[0];
        totalPosts = total.split(';')[1];
        $('#total-number-of-mentions .number').first().html(nFormatter(totalThreads));
        $('#total-number-of-mentions .number').last().html(nFormatter(totalPosts));
        var trendlineDate = [];
        var trendlineData = [];
        for (var item in r.data) {
            trendlineDate.push(item);
            trendlineData.push(r.data[item]);
        }
        var year = (new Date()).getFullYear();
        var date = new Date(trendlineDate[0] + ' ' + year);
        var month = date.getMonth();
        var day = date.getDate();
        $(function() {
            if ($('#widget-trendline').length === 0)
                return;
            addClass(document.getElementById('metrics-trendline').getElementsByClassName('trendline-loading')[0], 'hide');
            removeClass(document.getElementById('metrics-trendline'), 'load');
            $('#widget-trendline').highcharts({
                chart: {
                    type: 'areaspline',
                    spacingBottom: 0
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: '',
                    floating: true,
                    align: 'right',
                    verticalAlign: 'bottom',
                    y: 15
                },
                legend: {
                    layout: 'vertical',
                    align: 'left',
                    verticalAlign: 'top',
                    x: 150,
                    y: 100,
                    floating: true,
                    borderWidth: 1,
                    backgroundColor: 'transparent'
                },
                xAxis: {
                    gridLineWidth: 0,
                    tickWidth: 1,
                    lineWidth: 0,
                    type: 'datetime',
                    dateTimeLabelFormats: {
                        day: '%b %d',
                        week: '%b %d',
                    },
                    labels: {
                        overflow: 'justify'
                    }
                },
                yAxis: {
                    title: {
                        text: ''
                    },
                    showFirstLabel: false,
                    gridLineColor: '#C0C0C0',
                    gridLineWidth: 0,
                    labels: {
                        formatter: function() {
                            return this.value / 1000 + 'k';
                        }
                    },
                    endOnTick: false,
                    maxPadding: 0.1
                },
                tooltip: {
                    formatter: function() {
                        return '<b>' + this.series.name + '</b><br/>' + Highcharts.dateFormat('%b %d', this.x) + ': ' + this.y + ' mentions'
                    }
                },
                plotOptions: {
                    area: {
                        fillOpacity: 0.5
                    },
                    series: {
                        marker: {
                            fillColor: 'transparent',
                            lineWidth: 0,
                            lineColor: 'transparent', // inherit from series
                            states: {
                                hover: {
                                    lineWidth: 1,
                                    radius: 4,
                                    lineColor: '#EEE',
                                    fillColor: '#FFF'
                                }
                            }
                        }
                    }
                },
                credits: {
                    enabled: false
                },
                series: [{
                        name: 'Mentions',
                        data: trendlineData,
                        events: {
                            click: function(e) {
                                var date = new Date(e.point.x);
                                var trueDate = getTrueDate(date);
                                var displayDate = getDisplayDate(date);
                                $('#selected_date').attr('datefrom', trueDate);
                                $('#selected_date').attr('dateto', trueDate);
                                $('#selected_date').html(displayDate + ' - ' + displayDate);
                                $('#from').datepicker('setDate', trueDate);
                                $('#to').datepicker('setDate', trueDate);
                                $('#date-filter-widget .filter-button').addClass('selected');
                                setCookie('stream[' + streamId + '][datefrom]', trueDate, 1);
                                setCookie('stream[' + streamId + '][dateto]', trueDate, 1);
                                $('.url-widget-link').first().click();
                            }
                        },
                        pointStart: Date.UTC(year, month, day),
                        pointInterval: 24 * 3600 * 1000 // one day
                    }]
            });
        });  
        $('#widget-trendline .highcharts-container .highcharts-legend').attr('class', 'highcharts-legend hide');
        $('#widget-trendline .highcharts-container').height($('.highcharts-container').height() + 15);
        $('#widget-trendline .highcharts-container svg').height($('.highcharts-container svg').height() + 15);
    }

}

function nFormatter(num) {
    if (num > 999999)
        return (num / 1000000).toFixed(1) + 'M';
    if (num > 999)
        return (num / 1000).toFixed(1) + 'K';
    return num;
}


function loadTopSocialPlatforms() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    var filter = {};
    filter.streamId = streamId;
    filter.dateFrom = dateFrom;
    filter.dateTo = dateTo;
    filter.language = language.split(',');
    filter.tags = tag.split(',');
    filter.sentiment = sentiment;
    filter.type = type.split(',');
    filter.source = source.split(',');
    curRequests.push($.get('/ws/topsocialplatform/' + streamId + '/' + JSON.stringify(filter), function(r) {
        topSocialLoadCompleted(JSON.parse(r), filter);
        oldTopSocialLoadCompleted(JSON.parse(r), filter);
    }));
}

function oldTopSocialLoadCompleted(r, filter) {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    if (count(r) == 0) {
        $('#social_platforms ul li').remove();
        $('#social_platforms').parent().addClass('loaded');
    }
    if (count(r) > 0) {
        var dname = [];
        var data = [];
        for (var key in r) {
            if (key === 'authors' || key === 'threads')
                continue;
            dname.push(key);
            data.push(r[key]);
        }
        var social = {1: ['forum', 'fa fa-forums icon-boards-metrics', '#41A293'],
            2: ['news', 'ub ub-news icon-news-metrics', '#DD4B39'],
            3: ['blog', 'fa fa-blogs icon-blogs-metrics', '#E77800'],
            4: ['facebook', 'fa fa-facebook icon-facebook-metrics', '#3B5998'],
            5: ['twitter', 'ub ub-twitter icon-twitter-metrics', '#00ACED'],
            6: ['youtube', 'ub ub-youtube icon-youtube-metrics', '#D00707'],
            7: ['google+', 'ub ub-googleplus icon-googleplus-metrics', '#DD4B39'],
            9: ['retailers', 'ub ub-retailers icon-retailers-metrics', '#8E44AD'],
            8: ['classifieds', 'ub ub-classifieds icon-classifieds-metrics', '#02aa14']};
        var dtotal = arraySum(data);
        $('.top-platforms').empty();
        for (i = 0; i < dname.length; i++) {
            if (data[i] === 0)
                continue;
            dt = social[dname[i]];
            var html = '<li class="mozaic-widget social-platform widget-platform" data-widget="platform" data-params="" data-guid="widget-2187" data-initialized="true">' +
                    '<div id="graph' + dname[i] + '" style="" percent="0"></div>' +
                    '</div>' +
                    '<div class="mozaic-widget metrics-text-link widget-item_count" data-widget="item_count" data-params="" data-guid="widget-2197" data-initialized="true">' +
                    '<div>' +
                    '<i class="' + dt[1] + '"></i>' +
                    '<span class="number" data-id="twitter" rel="tooltip" data-title="' + data[i] + '" data-original-title="">' +
                    nFormatter(data[i]) +
                    '</span>' +
                    '<span class="text">' + dt[0] + '</span>' +
                    '</div>' +
                    '</div>' +
                    '<div class="social-hover"></div>\
                    <div id="subtrend' + dname[i] + '" style="height: 40px"></div></li>';
            $('.top-platforms').append(html);
            if (document.getElementById('graph' + dname[i]).childNodes.length != 0)
                $('#graph' + i).html('');
            socialGraph(document.getElementById('graph' + dname[i]), 2, 2, dt[2], 48, parseInt(parseInt(data[i]) / dtotal * 100));
            filter.type = dname[i];
            filter.color = dt[2].substring(1);
            curRequests.push($.get('/ws/trendline/' + filter.streamId + '/' + JSON.stringify(filter), function(st) {
                st = JSON.parse(st);
            }));
        }
        addClass(document.getElementById('social_platforms').parentElement.getElementsByClassName('social-platforms-loading')[0], 'hide');
        removeClass(document.getElementById('social_platforms').parentElement, 'load');        
        $('.top-platforms').parents('.metrics-block').addClass('loaded');
        inte = setInterval('increasePercent()', 5);
    }
    else {
        $('#social_platforms ul li').remove();
        $('#social_platforms').parent().addClass('loaded');
    }
}

function arraySum(array) {
    var sum = 0;
    if (array.length !== undefined) {
        if (array.length > 0)
            for (i = 0; i < array.length; i++)
                sum += array[i];
    } else {
        for (var key in array) {
            sum += array[key];
        }
    }
    return sum;
}

var count = function(object) {
    var c = 0;
    for (var key in object) {
        c++;
    }
    return c;
}

var topSocialPlatform = [];
var topSocialPlatformPie;
function drawTopSocialPlatformPie(element, data) {
    $(function() {
        topSocialPlatformPie = element.highcharts({
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: 0,
                plotShadow: false,
            },
            title: {
                text: ''
            },
            tooltip: {
                pointFormat: '<b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    size: null,
                    dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',
                        format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                    }
                }
            },
            credits: {
                enabled: false
            },
            legends: {
                enabled: false,
            },
            series: [{
                    type: 'pie',
                    name: '',
                    data: data
                }]
        });
    });
}

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

var topSocialPlatformTrend = [];
var chartCount = 0;
function topSocialLoadCompleted(r, filter) {
    topSocialPlatformTrend = [];
    chartCount = 0;
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    if (count(r) === 0) {
        $('#social_platforms ul li').remove();
        $('#social_platforms').parent().addClass('loaded');
    }
    if (count(r) > 0) {
        var dname = [];
        var data = [];
        for (var key in r) {
            if (key === 'authors' || key === 'threads')
                continue;
            dname.push(key);
            data.push(r[key]);
        }
        var social = {1: ['forum', 'icon-boards-metrics', '#41A293'],
            2: ['news', 'icon-news-metrics', '#DD4B39'],
            3: ['blog', 'icon-blogs-metrics', '#E77800'],
            4: ['facebook', 'icon-facebook-metrics', '#3B5998'],
            5: ['twitter', 'icon-twitter-metrics', '#00ACED'],
            6: ['youtube', 'icon-youtube-metrics', '#D00707'],
            7: ['google+', 'icon-googleplus-metrics', '#DD4B39'],
            9: ['retailers', 'icon-retailers-metrics', '#8E44AD'],
            8: ['classifieds', 'icon-classifieds-metrics', '#02aa14']};
        var dtotal = arraySum(data);
        $('.top-platforms').empty();
        var topSocialData = [];
        topSocialPlatform = [];
        for (i = 0; i < dname.length; i++) {
            if (data[i] > 0) {
                dt = social[dname[i]];
                topSocialPlatform.push(dname[i]);
                topSocialData.push({
                    name: toTitleCase(dt[0]),
                    color: dt[2],
                    y: data[i]
                });
            }
        }
        drawTopSocialPlatformPie($('#top-social-platform-overall'), topSocialData);
        for (i = 0; i < dname.length; i++) {
            if (data[i] === 0)
                continue;
            dt = social[dname[i]];
            //draw using highcharts

            filter.type = dname[i];
            filter.color = dt[2].substring(1);
            var year = (new Date()).getFullYear();
            var date = new Date(trendlineDate[0] + ' ' + year);
            var month = date.getMonth();
            var day = date.getDate();
            curRequests.push($.get('/ws/trendline/' + filter.streamId + '/' + JSON.stringify(filter), function(st) {
                st = JSON.parse(st);
                if (count(st) > 0) {
                    var trendlineDate = [];
                    var trendlineData = [];
                    for (var item in st.data) {
                        trendlineDate.push(item);
                        trendlineData.push(st.data[item]);
                    }
                    topSocialPlatformTrend.push({
                        name: toTitleCase(social[st.filter.type][0]),
                        data: trendlineData,
                        color: '#' + st.filter.color,
                        fillOpacity: 1,
                        events: {
                            legendItemClick: topSocialLegendClick
                        },
                        pointStart: Date.UTC(year, month, day),
                        pointInterval: 24 * 3600 * 1000 // one day
                    });

                    $(function() {
                        var i = st.filter.type;
                        if ($('#subtrend' + i).length == 0)
                            return;
                        $('#subtrend' + i).highcharts({
                            chart: {
                                type: 'areaspline',
                                spacingBottom: 0
                            },
                            title: {
                                text: ''
                            },
                            subtitle: {
                                text: '',
                                floating: true,
                                align: 'right',
                                verticalAlign: 'bottom',
                                y: 15
                            },
                            legend: {
                                layout: 'vertical',
                                align: 'left',
                                verticalAlign: 'top',
                                x: 150,
                                y: 100,
                                floating: true,
                                borderWidth: 1,
                                backgroundColor: 'transparent'
                            },
                            xAxis: {
                                gridLineWidth: 0,
                                tickWidth: 0,
                                lineWidth: 0,
                                labels: {
                                    enabled: false
                                },
                                categories: trendlineDate
                            },
                            yAxis: {
                                title: {
                                    text: ''
                                },
                                showFirstLabel: false,
                                gridLineColor: '#C0C0C0',
                                gridLineDashStyle: 'Dot',
                                gridLineWidth: 0,
                                labels: {
                                    enabled: false
                                },
                                endOnTick: false,
                                maxPadding: 0.1
                            },
                            tooltip: {
                                enabled: false
                            },
                            plotOptions: {
                                area: {
                                    fillOpacity: 0.5
                                },
                                series: {
                                    marker: {
                                        fillColor: 'transparent',
                                        lineWidth: 0,
                                        lineColor: 'transparent', // inherit from series
                                        states: {
                                            hover: {
                                                lineWidth: 0,
                                                radius: 1,
                                                lineColor: '#EEE',
                                                fillColor: '#FFF'
                                            }
                                        }
                                    }
                                }
                            },
                            credits: {
                                enabled: false
                            },
                            series: [{
                                    name: 'Mentions',
                                    data: trendlineData,
                                    color: '#' + st.filter.color,
                                    events: {
                                        click: function(e) {
                                            var curDate = new Date();
                                            var date = new Date(e.point.category + ' ' + curDate.getFullYear());
                                            var trueDate = getTrueDate(date);
                                            var displayDate = getDisplayDate(date);
                                            $('#selected_date').attr('datefrom', trueDate);
                                            $('#selected_date').attr('dateto', trueDate);
                                            $('#selected_date').html(displayDate + ' - ' + displayDate);
                                            $('#from').datepicker('setDate', trueDate);
                                            $('#to').datepicker('setDate', trueDate);
                                            $('#date-filter-widget .filter-button').addClass('selected');
                                            $('.url-widget-link').first().click();
                                        }
                                    },
                                }]
                        });
                    });
                }
                chartCount++;
                if (chartCount === topSocialPlatform.length) {
                    $(function() {
                        $('#top-social-platform-widget').parents('.metrics-block').addClass('loaded');
                        chartT = $('#top-social-platform-widget').highcharts({
                            chart: {
                                type: 'areaspline'
                            },
                            title: {
                                text: ''
                            },
                            subtitle: {
                                text: ''
                            },
                            legend: {
                                borderWidth: 0,
                            },
                            xAxis: {
                                gridLineWidth: 0,
                                tickWidth: 1,
                                lineWidth: 0,
                                type: 'datetime',
                                dateTimeLabelFormats: {
                                    day: '%b %d',
                                    week: '%b %d'
                                }, labels: {
                                    overflow: 'justify'
                                }
                            },
                            yAxis: {
                                title: {
                                    text: ''
                                },
                                showFirstLabel: false,
                                gridLineWidth: 0,
                                labels: {
                                    formatter: function() {
                                        return this.value / 1000 + 'k';
                                    }
                                },
                                endOnTick: false,
                                maxPadding: 0.1
                            },
                            tooltip: {
                                pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.x.percentage:.1f}%</b> ({point.y:,.0f} mentions)<br/>',
                                shared: true
                            },
                            plotOptions: {
                                area: {
                                    lineColor: '#ffffff',
                                    lineWidth: 1,
                                    marker: {
                                        lineWidth: 1,
                                        lineColor: '#ffffff'
                                    },
                                },
                                series: {
                                    stacking: 'normal',
                                    marker: {
                                        fillColor: 'transparent',
                                        lineWidth: 0,
                                        lineColor: 'transparent', // inherit from series
                                        states: {
                                            hover: {
                                                lineWidth: 1,
                                                radius: 4,
                                                lineColor: '#EEE',
                                                fillColor: '#FFF'
                                            }
                                        }
                                    }
                                }
                            },
                            credits: {
                                enabled: false
                            },
                            series: topSocialPlatformTrend
                        });
                    });
                }
            }));
        }
        $('.top-platforms').parents('.metrics-block').addClass('loaded');
        inte = setInterval('increasePercent()', 5);
    }
    else {
        $('#social_platforms ul li').remove();
        $('#social_platforms').parent().addClass('loaded');
    }
    addClass(document.getElementById('metrics-top-social-platform').parentElement.getElementsByClassName('top-social-platforms-loading')[0], 'hide');
    removeClass(document.getElementById('metrics-top-social-platform').parentElement, 'load'); 
}

function topSocialLegendClick() {
    var name = this.name;
    var lineChart = this;
    $(topSocialPlatformPie.highcharts().series[0].data).each(function(k, z) {
        if (z.name == name) {
            z.setVisible(!lineChart.visible);
        }
    });
}

function loadSharingMetrics() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    streamId = window.location.href.split('#')[1].split('/')[1];
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = $('#language-filter-widget a').first().attr('data-value');
    tags = $('#tag-filter-widget a').first().attr('data-value');
    sentiment = $('.radio-options-sentiment .selected').attr('data-value');
    type = $('#platform-filter-widget').find('a').attr('data-value');
    source = $('#source-filter-widget a').first().attr('data-value');
    var pl = new SOAPClientParameters();
    pl.add("typedata", "filter");
    pl.add("streamId", streamId);
    pl.add("dateFrom", dateFrom);
    pl.add("dateTo", dateTo);
    pl.add("language", language);
    pl.add("tags", tags);
    pl.add("sentiment", sentiment);
    pl.add("type", type);
    pl.add("source", source);
    SOAPClient.invoke("/m/", "getSharingMetricsData", pl, true, sharingMetricsLoadCompleted);
}

function sharingMetricsLoadCompleted(r) {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    if (r) {
        data = r.data.split(';');
        $('#sharing_metrics .fb-shares .number').html(data[0]);
        $('#sharing_metrics .tw-retweets .number').html(data[1]);
    }
}

function loadSentimentData() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    $('#sentiment-trend').parents('.metrics-block').removeClass('loaded');
    streamId = window.location.href.split('#')[1].split('/')[1];
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = $('#language-filter-widget a').first().attr('data-value');
    tags = $('#tag-filter-widget a').first().attr('data-value');
    sentiment = $('.radio-options-sentiment .selected').attr('data-value');
    type = $('#platform-filter-widget').find('a').attr('data-value');
    source = $('#source-filter-widget a').first().attr('data-value');
    var filter = {};
    filter.streamId = streamId;
    filter.dateFrom = dateFrom;
    filter.dateTo = dateTo;
    filter.language = language;
    filter.tags = tags;
    filter.sentiment = sentiment;
    filter.type = type;
    filter.source = source;
    curRequests.push($.get('/ws/sentiment/' + streamId + '/' + JSON.stringify(filter), function(r) {
        sentimentDataLoadCompleted(JSON.parse(r));
    }));
}
var chartPercents;
var chartT, chartSentimentPercent;
var sentimentData = {};
function sentimentDataLoadCompleted(r) {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    if (count(r) > 0) {
        var percents = [];
        var dates = [];
        var positive = [], neutral = [], negative = [], undefine = [], irrelevant = [];
        chartPercents = {};
        for (var key in r) {
            dates.push(key);
            if (r[key][1] !== undefined)
                positive.push(r[key][1]);
            else
                positive.push(0);
            if (r[key][0] !== undefined)
                neutral.push(r[key][0]);
            else
                neutral.push(0);
            if (r[key][ -1] !== undefined)
                negative.push(r[key][ -1]);
            else
                negative.push(0);
            if (r[key][ -2] !== undefined)
                undefine.push(r[key][ -2]);
            else
                undefine.push(0);
            if (r[key][ -3] !== undefined)
                irrelevant.push(r[key][ -3]);
            else
                irrelevant.push(0);
            var total = arraySum(r[key]);
            chartPercents[key] = [];
            if (r[key][1] === undefined)
                chartPercents[key][1] = 0;
            else
                chartPercents[key][1] = r[key][1] / total;
            if (r[key][0] === undefined)
                chartPercents[key][0] = 0;
            else
                chartPercents[key][0] = r[key][0] / total;
            if (r[key][ -1] === undefined)
                chartPercents[key][ -1] = 0;
            else
                chartPercents[key][ -1] = r[key][ -1] / total;
            if (r[key][ -2] === undefined)
                chartPercents[key][ -2] = 0;
            else
                chartPercents[key][ -2] = r[key][ -2] / total;
            if (r[key][ -3] === undefined)
                chartPercents[key][ -3] = 0;
            else
                chartPercents[key][ -3] = r[key][ -3] / total;
        }

        sentimentData.positive = positive;
        sentimentData.negative = negative;
        sentimentData.neutral = neutral;
        sentimentData.undefine = undefine;
        sentimentData.irrelevant = irrelevant;

        var posTotal = arraySum(positive);
        var neuTotal = arraySum(neutral);
        var negTotal = arraySum(negative);
        var irrTotal = arraySum(irrelevant);
        var undTotal = arraySum(undefine);
        var total = arraySum([posTotal, neuTotal, negTotal, undTotal, irrTotal]);
        percents.push(Math.round(posTotal / total * 1000) / 10);
        percents.push(Math.round(neuTotal / total * 1000) / 10);
        percents.push(Math.round(negTotal / total * 1000) / 10);
        percents.push(Math.round(irrTotal / total * 1000) / 10);
        percents.push(Math.round((100 - arraySum(percents)) * 10) / 10);
        tds = $('.sentiment-data td');
        for (i = 0; i < 5; i++) {
            tds[i].innerHTML = percents[i];
            if (percents[i].toFixed(0) == 0)
                $('.sentiment-graph-details li')[i].style.display = 'none';
            else
                $('.sentiment-graph-details li')[i].style.display = '';
            $('.sentiment-graph-details li')[i].style.width = percents[i] + '%';
            if ($($('.sentiment-graph-details li')[i]).find('span').first().length > 0)
                $($('.sentiment-graph-details li')[i]).find('span').first().html(percents[i] + '%');
        }
        renderOveralSentiment(percents);
        if ($('.sentiment-trend.selected').text() == 'SENTIMENT TREND')
            drawPercentTrend(sentimentData, 'normal');
        else
            drawPercentTrend(sentimentData, 'percent');
    }
    metricsProcessing = false;
}

function drawPercentTrend(data, stacking) {
    var date = new Date(dateFText + ' ');
    var year = (new Date()).getFullYear();
    var month = date.getMonth();
    var day = date.getDate();
    $(function() {
        if ($('#sentiment-trend').length === 0)
            return;
        $('#sentiment-trend').parents('.metrics-block').addClass('loaded');
        chartT = $('#sentiment-trend').highcharts({
            chart: {
                type: 'areaspline'
            },
            title: {
                text: ''
            },
            subtitle: {
                text: ''
            },
            legend: {
                borderWidth: 0,
            },
            xAxis: {
                gridLineWidth: 0,
                tickWidth: 1,
                lineWidth: 0,
                type: 'datetime',
                dateTimeLabelFormats: {
                    day: '%b %d',
                    week: '%b %d'
                }, labels: {
                    overflow: 'justify'
                }
            },
            yAxis: {
                title: {
                    text: ''
                },
                showFirstLabel: false,
                gridLineWidth: 0,
                labels: {
                    formatter: function() {
                        return this.value / 1000 + 'k';
                    }
                },
                endOnTick: false,
                maxPadding: 0.1
            },
            tooltip: {
                pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.x.percentage:.1f}%</b> ({point.y:,.0f} mentions)<br/>',
                shared: true
            },
            plotOptions: {
                area: {
                    lineColor: '#ffffff',
                    lineWidth: 1,
                    marker: {
                        lineWidth: 1,
                        lineColor: '#ffffff'
                    },
                },
                series: {
                    stacking: stacking,
                    marker: {
                        fillColor: 'transparent',
                        lineWidth: 0,
                        lineColor: 'transparent', // inherit from series
                        states: {
                            hover: {
                                lineWidth: 1,
                                radius: 4,
                                lineColor: '#EEE',
                                fillColor: '#FFF'
                            }
                        }
                    },
                    dataGrouping: {
                        units: 'week'
                    }
                }
            },
            credits: {
                enabled: false
            },
            series: [{
                    name: 'Negative',
                    data: data.negative,
                    color: "#c0504d",
                    fillOpacity: 1,
                    events: {
                        click: function(e) {
                            $('.radio-options-sentiment a.selected').removeClass('selected');
                            $($('.radio-options-sentiment a')[2]).addClass('selected');
                            var date = new Date(e.point.x);
                            var trueDate = getTrueDate(date);
                            var displayDate = getDisplayDate(date);
                            $('#selected_date').attr('datefrom', trueDate);
                            $('#selected_date').attr('dateto', trueDate);
                            $('#selected_date').html(displayDate + ' - ' + displayDate);
                            $('#from').datepicker('setDate', trueDate);
                            $('#to').datepicker('setDate', trueDate);
                            $('#date-filter-widget .filter-button').addClass('selected');
                            setCookie('stream[' + streamId + '][datefrom]', $("#from").datepicker().val(), 1);
                            setCookie('stream[' + streamId + '][dateto]', $("#to").datepicker().val(), 1);
                            $('.url-widget-link').first().click();
                            //$('.url-widget-link').first().click();
                        },
                        legendItemClick: sentimentLegendClick
                    },
                    pointStart: Date.UTC(year, month, day),
                    pointInterval: 24 * 3600 * 1000 // one day
                }, {
                    name: 'Neutral',
                    data: data.neutral,
                    color: "#9bbb59",
                    fillOpacity: 1,
                    events: {
                        click: function(e) {
                            $('.radio-options-sentiment a.selected').removeClass('selected');
                            $($('.radio-options-sentiment a')[1]).addClass('selected');
                            var date = new Date(e.point.x);
                            var trueDate = getTrueDate(date);
                            var displayDate = getDisplayDate(date);
                            $('#selected_date').attr('datefrom', trueDate);
                            $('#selected_date').attr('dateto', trueDate);
                            $('#selected_date').html(displayDate + ' - ' + displayDate);
                            $('#from').datepicker('setDate', trueDate);
                            $('#to').datepicker('setDate', trueDate);
                            $('#date-filter-widget .filter-button').addClass('selected');
                            setCookie('stream[' + streamId + '][datefrom]', $("#from").datepicker().val(), 1);
                            setCookie('stream[' + streamId + '][dateto]', $("#to").datepicker().val(), 1);
                            $('.url-widget-link').first().click();
                            //$('.url-widget-link').first().click();
                        },
                        legendItemClick: sentimentLegendClick
                    },
                    pointStart: Date.UTC(year, month, day),
                    pointInterval: 24 * 3600 * 1000 // one day
                },
                {
                    name: 'Positive',
                    data: data.positive,
                    color: "#4f81bd",
                    fillOpacity: 1,
                    events: {
                        click: function(e) {
                            $('.radio-options-sentiment a.selected').removeClass('selected');
                            $($('.radio-options-sentiment a')[0]).addClass('selected');
                            var date = new Date(e.point.x);
                            var trueDate = getTrueDate(date);
                            var displayDate = getDisplayDate(date);
                            $('#selected_date').attr('datefrom', trueDate);
                            $('#selected_date').attr('dateto', trueDate);
                            $('#selected_date').html(displayDate + ' - ' + displayDate);
                            $('#from').datepicker('setDate', trueDate);
                            $('#to').datepicker('setDate', trueDate);
                            $('#date-filter-widget .filter-button').addClass('selected');
                            setCookie('stream[' + streamId + '][datefrom]', $("#from").datepicker().val(), 1);
                            setCookie('stream[' + streamId + '][dateto]', $("#to").datepicker().val(), 1);
                            $('.url-widget-link').first().click();
                            //$('.url-widget-link').first().click();
                        },
                        legendItemClick: sentimentLegendClick
                    },
                    pointStart: Date.UTC(year, month, day),
                    pointInterval: 24 * 3600 * 1000 // one day
                }, {
                    name: 'Irrelevant',
                    data: data.irrelevant,
                    color: "#ffe563",
                    fillOpacity: 1,
                    pointStart: Date.UTC(year, month, day),
                    pointInterval: 24 * 3600 * 1000, // one day
                    events: {
                        legendItemClick: sentimentLegendClick
                    }
                }, {
                    name: 'Undefined',
                    data: data.undefine,
                    color: "#BBB",
                    fillOpacity: 1,
                    pointStart: Date.UTC(year, month, day),
                    pointInterval: 24 * 3600 * 1000, // one day
                    events: {
                        legendItemClick: sentimentLegendClick
                    }
                }
            ]
        }, function(chart) {
            if (chartPercents !== undefined)
                chart.tooltip.options.formatter = function() {
                    var xyArr = [];
                    $.each(this.points, function() {
                        var perI = 0;
                        if (this.series.name === 'Positive')
                            perI = 1;
                        if (this.series.name === 'Neutral')
                            perI = 0;
                        if (this.series.name === 'Negative')
                            perI = -1;
                        if (this.series.name === 'Undefined')
                            perI = -2;
                        if (this.series.name === 'Irrelevant')
                            perI = -3;
                        xyArr.push('<span style="color:' + this.series.color + '">' + this.series.name + '</span>: <b>' + Math.round(chartPercents[Highcharts.dateFormat('%b %d', this.x)][perI] * 1000) / 10 + '%</b> (' + this.point.y + ' mentions)');
                    });
                    return xyArr.join('<br/>');
                }
        });
    });
}

function sentimentLegendClick(e) {
    var name = this.name;
    var lineChart = this;
    $(sentimentPie.highcharts().series[0].data).each(function(k, z) {
        if (z.name == name) {
            z.setVisible(!lineChart.visible);
        }
        else {
            $('.sentiment-graph-details li')[k].style.display = '';
        }
    });

    $(sentimentPie.highcharts().series[0].data).each(function(k, z) {
        if (!z.visible)
            $('.sentiment-graph-details li')[k].style.display = 'none';
        else
            $('.sentiment-graph-details li')[k].style.display = '';
        $('.sentiment-graph-details li')[k].style.width = sentimentPie.highcharts().series[0].data[k].percentage + '%';
        if ($('.sentiment-graph-details .sentiment-graph-details-percentage')[k] !== undefined)
            $('.sentiment-graph-details .sentiment-graph-details-percentage')[k].innerHTML = Math.round(sentimentPie.highcharts().series[0].data[k].percentage * 10) / 10 + '%'
    });
}
var sentimentPie;
function renderOveralSentiment(data) {
    $(function() {
        if ($('#sentiment-metter').length == 0)
            return;
        sentimentPie = $('#sentiment-metter').highcharts({
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: 0,
                plotShadow: false,
                events: {
                    load: function(e) {
                        $(this.data).each(function(k, z) {
                            if (!z.visible)
                                $('.sentiment-graph-details li')[k].style.display = 'none';
                            else
                                $('.sentiment-graph-details li')[k].style.display = '';
                            $('.sentiment-graph-details li')[k].style.width = sentimentPie.highcharts().series[0].data[k].percentage + '%';
                            if ($('.sentiment-graph-details .sentiment-graph-details-percentage')[k] !== undefined)
                                $('.sentiment-graph-details .sentiment-graph-details-percentage')[k].innerHTML = Math.round(sentimentPie.highcharts().series[0].data[k].percentage * 10) / 10 + '%'
                        });
                    }
                }
            },
            title: {
                text: ''
            },
            tooltip: {
                pointFormat: '<b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    size: 160,
                    dataLabels: {
                        enabled: false
                    },
                    startAngle: -90,
                    endAngle: 90,
                    center: ["50%", "130%"]
                }
            },
            credits: {
                enabled: false
            },
            legends: {
                enabled: false,
            },
            series: [{
                    type: 'pie',
                    name: '',
                    innerSize: '95%',
                    data: [
                        {name: 'Positive',
                            y: data[0],
                            color: "#4f81bd",
                            fillOpacity: 1,
                            events: {
                                click: function(e) {
                                    $('.radio-options-sentiment a.selected').removeClass('selected');
                                    $($('.radio-options-sentiment a')[0]).addClass('selected');
                                    $('.url-widget-link').first().click();
                                }
                            }
                        },
                        {name: 'Neutral',
                            y: data[1],
                            color: "#9bbb59",
                            fillOpacity: 1,
                            events: {
                                click: function(e) {
                                    $('.radio-options-sentiment a.selected').removeClass('selected');
                                    $($('.radio-options-sentiment a')[1]).addClass('selected');
                                    $('.url-widget-link').first().click();
                                }
                            }
                        },
                        {name: 'Negative',
                            y: data[2],
                            color: "#c0504d",
                            fillOpacity: 1,
                            events: {
                                click: function(e) {
                                    $('.radio-options-sentiment a.selected').removeClass('selected');
                                    $($('.radio-options-sentiment a')[2]).addClass('selected');
                                    $('.url-widget-link').first().click();
                                }
                            }
                        },
                        {
                            name: 'Irrelevant',
                            y: data[3],
                            color: "#ffe563",
                            fillOpacity: 1
                        },
                        {
                            name: 'Undefined',
                            y: data[4],
                            color: "#BBB",
                            fillOpacity: 1
                        }
                    ]
                }]
        });
    });
}

var tagData;
function loadTagMetric() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    $('.tag-block').removeClass('loaded');
    $('.tag-block:not(:first)').remove();
    var streamId = window.location.href.split('#')[1].split('/')[1];
    var pl = new SOAPClientParameters();
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    streamId = window.location.href.split('#')[1].split('/')[1];
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = $('#language-filter-widget a').first().attr('data-value');
    tags = $('#tag-filter-widget a').first().attr('data-value');
    sentiment = $('.radio-options-sentiment .selected').attr('data-value');
    type = $('#platform-filter-widget').find('a').attr('data-value');
    source = $('#source-filter-widget a').first().attr('data-value');
    var filter = {};
    filter.streamId = streamId;
    filter.dateFrom = dateFrom;
    filter.dateTo = dateTo;
    filter.language = language;
    filter.tags = tags;
    filter.sentiment = sentiment;
    filter.type = type;
    filter.source = source;
    curRequests.push($.get('/ws/tagsmetric/' + streamId + '/' + JSON.stringify(filter), function(r) {
        tagsMetricLoadComplete(JSON.parse(r));
    }));
}
var tagGroups = {};
function tagsMetricLoadComplete(data) {
    tagData = data;
    if (count(tagData) == 0) {
        $('.tag-block').css('height', '0');
        $('.tag-block').addClass('loaded');
    }
    var numOfGroups = count(tagData);
    var index = 0;
    if (numOfGroups < $('.tag-block').length) {
        for (var i = numOfGroups; i < $('.tag-block').length; i++) {
            $('.tag-block')[i].style.height = '0px';
            $($('.tag-block')[i]).addClass('loaded');
        }
    }
    for (var tagGroup in tagData) {
        if (index == 0) {
            $('#block1 h5').text(tagGroup.toUpperCase());
            $('#block1 h5').attr('text', tagGroup);
        }
        if (index > 0 && $('.tag-block').length < numOfGroups) {
            var tagBlock = '<div id="block' + (index + 1) + '" class="row-fluid white-row metrics-block tag-block" style="width: 50%">\
                                <div class="">\
                                    <h5 text="' + tagGroup + '">' + tagGroup.toUpperCase() + '</h5>\
                                    <div class="mozaic-widget widget-top_tags">\
                                        <div id="top_tags">\
                                            <div id="top-tags-inner' + (index + 1) + '" style="height: 300px; width: 96%; padding-left: 20px;">\
                                            </div>\
                                        </div>\
                                    </div>\
                                </div>\
                                <div class="loading" style="left: 46%;top: 49%;position: absolute;">\
                                    <div class="duo duo1">\
                                        <div class="dot dot-a"></div>\
                                        <div class="dot dot-b"></div>\
                                    </div>\
                                    <div class="duo duo2">\
                                        <div class="dot dot-a"></div>\
                                        <div class="dot dot-b"></div>\
                                    </div>\
                                </div>\
                            </div>';
            $('.tag-block:last').after(tagBlock);
            $('.tag-block').css('display', 'inline-block');
            if (numOfGroups % 2 == 1) {
                $('.tag-block:not(:first)').css('width', '50%');
            }
            else {
                $('.tag-block:not(:first)').css('width', '50%');
                $('.tag-block:last').css('width', '100%');
            }
            setTimeout(function() {
                $(window).resize();
            }, 500);
        }
        var tname = tagData[tagGroup].tagname;
        var tickPositions = [];
        var pos = [];
        var neg = [];
        var neu = [];
        for (var i = 0; i < tname.length; i++) {
            if (tagData[tagGroup][tname[i]][0] !== undefined)
                neu[i] = parseInt(tagData[tagGroup][tname[i]][0]);
            else
                neu[i] = 0;
            if (tagData[tagGroup][tname[i]][1] !== undefined)
                pos[i] = parseInt(tagData[tagGroup][tname[i]][1]);
            else
                pos[i] = 0;
            if (tagData[tagGroup][tname[i]][ -1] !== undefined)
                neg[i] = parseInt(tagData[tagGroup][tname[i]][ -1]);
            else
                neg[i] = 0;
            tickPositions.push(i);
            tagGroups[tname[i]] = tagGroup;
        }
        var chartHeight = 20 * tname.length + 60;
        $('#top-tags-inner' + (index + 1)).css('height', chartHeight + 'px');
        $('#block' + (index + 1)).css('height', chartHeight + 20 + 'px');
        $(function() {
            if ($('#top-tags-inner' + (index + 1)).length == 0)
                return;
            $('#top-tags-inner' + (index + 1)).parents('.metrics-block').addClass('loaded');
            $('#top-tags-inner' + (index + 1)).highcharts({
                chart: {
                    type: 'bar'
                },
                title: {
                    text: ''
                },
                xAxis: {
                    categories: tname,
                    tickPositions: tickPositions,
                    title: {
                        text: null
                    }
                },
                yAxis: {
                    min: 0,
                    minTickInterval: 1,
                    gridLineWidth: 0,
                    title: {
                        text: null,
                        align: 'high'
                    },
                    labels: {
                        overflow: 'justify',
                        enabled: false
                    }
                },
                tooltip: {
                    enabled: true,
                },
                plotOptions: {
                    bar: {
                        dataLabels: {
                            enabled: false
                        }
                    },
                    series: {
                        stacking: 'normal',
                        pointWidth: 15,
                        pointPadding: 1
                    }
                },
                legend: {
                    enabled: true,
                    reversed: true,
                    borderWidth: 0
                },
                credits: {
                    enabled: false
                },
                series: [{
                        name: 'Negative',
                        data: neg,
                        color: "#c0504d",
                        events: {
                            click: function(e) {
                                var category = e.point.category;
                                var group = tagGroups[category];
                                var tagid = tagData[group][category]['id'];
                                $('#tag-filter-widget>div>a').attr('data-value', tagid);
                                $('#selected-tag').text(category);
                                $('#tag-filter-widget>div').addClass('selected');
                                $('.radio-options-sentiment>a').last().addClass('selected');
                                $('#mentions-link-widget>a').click();
                            }
                        },
                        index: 0
                    }, {
                        name: 'Neutral',
                        data: neu,
                        color: "#9bbb59",
                        events: {
                            click: function(e) {
                                var category = e.point.category;
                                var group = tagGroups[category];
                                var tagid = tagData[group][category]['id'];
                                $('#tag-filter-widget>div>a').attr('data-value', tagid);
                                $('#selected-tag').text(category);
                                $('#tag-filter-widget>div').addClass('selected');
                                $('.radio-options-sentiment>a').last().prev().addClass('selected');
                                $('#mentions-link-widget>a').click();
                            }
                        },
                        visible: false,
                        index: 0
                    }, {
                        name: 'Positive',
                        data: pos,
                        color: "#4f81bd",
                        events: {
                            click: function(e) {
                                var category = e.point.category;
                                var group = tagGroups[category];
                                var tagid = tagData[group][category]['id'];
                                $('#tag-filter-widget>div>a').attr('data-value', tagid);
                                $('#selected-tag').text(category);
                                $('#tag-filter-widget>div').addClass('selected');
                                $('.radio-options-sentiment>a').first().addClass('selected');
                                $('#mentions-link-widget>a').click();
                            }
                        },
                        index: 1
                    }]
            });
        });
        index++;
    }
}

function loadTagsComparison() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    $('.tag-comparison-block').removeClass('loaded');
    $('.tag-comparison-block:not(:first)').remove();
    var streamId = window.location.href.split('#')[1].split('/')[1];
    var pl = new SOAPClientParameters();
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    streamId = window.location.href.split('#')[1].split('/')[1];
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = $('#language-filter-widget a').first().attr('data-value');
    tags = $('#tag-filter-widget a').first().attr('data-value');
    sentiment = $('.radio-options-sentiment .selected').attr('data-value');
    type = $('#platform-filter-widget').find('a').attr('data-value');
    source = $('#source-filter-widget a').first().attr('data-value');
    var filter = {};
    filter.streamId = streamId;
    filter.dateFrom = dateFrom;
    filter.dateTo = dateTo;
    filter.language = language;
    filter.tags = tags;
    filter.sentiment = sentiment;
    filter.type = type;
    filter.source = source;
    curRequests.push($.get('/ws/tagscomparison/' + streamId + '/' + JSON.stringify(filter), function(r) {
        tagsComparisonLoadComplete(JSON.parse(r));
    }));
}

var tagComparisonData = {}, tagComparisonGroups = {};
function tagsComparisonLoadComplete(data) {
    tagComparisonData = data;
    if (count(tagComparisonData) == 0) {
        $('.tag-comparison-block').css('height', '0');
        $('.tag-comparison-block').addClass('loaded');
    }
    var numOfGroups = count(tagComparisonData);
    var index = 0;
    if (numOfGroups < $('.tag-comparison-block').length) {
        for (var i = numOfGroups; i < $('.tag-comparison-block').length; i++) {
            $('.tag-comparison-block')[i].style.height = '0px';
            $($('.tag-comparison-block')[i]).addClass('loaded');
        }
    }
    for (var tagGroup in tagComparisonData) {
        if (index == 0) {
            $('#cblock1 h5').text('COMPARE WITH ' + tagGroup.toUpperCase());
            $('#cblock1 h5').attr('text', 'COMPARE WITH ' + tagGroup);
        }
        if (index > 0 && $('.tag-comparison-block').length < numOfGroups) {
            var tagBlock = '<div id="cblock' + (index + 1) + '" class="row-fluid white-row metrics-block tag-comparison-block" style="width: 50%">\
                                <div class="">\
                                    <h5 text="' + tagGroup + '">COMPARE WITH ' + tagGroup.toUpperCase() + '</h5>\
                                    <div class="mozaic-widget widget-top_tags">\
                                        <div id="top_tags">\
                                            <div id="top-ctags-inner' + (index + 1) + '" style="height: 300px; width: 96%; padding-left: 20px;">\
                                            </div>\
                                        </div>\
                                    </div>\
                                </div>\
                                <div class="loading" style="left: 46%;top: 49%;position: absolute;">\
                                    <div class="duo duo1">\
                                        <div class="dot dot-a"></div>\
                                        <div class="dot dot-b"></div>\
                                    </div>\
                                    <div class="duo duo2">\
                                        <div class="dot dot-a"></div>\
                                        <div class="dot dot-b"></div>\
                                    </div>\
                                </div>\
                            </div>';
            $('.tag-comparison-block:last').after(tagBlock);
            if (numOfGroups % 2 == 1) {
                $('.tag-comparison-block:not(:first)').css('width', '50%');
            }
            else {
                $('.tag-comparison-block:not(:first)').css('width', '50%');
                $('.tag-comparison-block:last').css('width', '100%');
            }
            setTimeout(function() {
                $(window).resize();
            }, 1000);
        }
        setTimeout(function() {
            var blocks = $('.tag-comparison-block');
            for (var k = 2; k <= blocks.length; k++) {
                var leftBlock = $('#cblock' + k++);
                var rightBlock = $('#cblock' + k);
                if ($(leftBlock).height() < $(rightBlock).height()) {
                    $(leftBlock).height($(rightBlock).height());
                }
                else {
                    $(rightBlock).height($(leftBlock).height());
                }
            }
        }, 500);
        var tname = tagComparisonData[tagGroup].tagname;
        var tickPositions = [];
        var pos = [];
        var neg = [];
        var neu = [];
        for (i = 0; i < tname.length; i++) {
            if (tagComparisonData[tagGroup][tname[i]][0] !== undefined)
                neu[i] = parseInt(tagComparisonData[tagGroup][tname[i]][0]);
            else
                neu[i] = 0;
            if (tagComparisonData[tagGroup][tname[i]][1] !== undefined)
                pos[i] = parseInt(tagComparisonData[tagGroup][tname[i]][1]);
            else
                pos[i] = 0;
            if (tagComparisonData[tagGroup][tname[i]][ -1] !== undefined)
                neg[i] = parseInt(tagComparisonData[tagGroup][tname[i]][ -1]);
            else
                neg[i] = 0;
            tickPositions.push(i);
            tagComparisonGroups[tname[i]] = tagGroup;
        }
        var chartHeight = 20 * tname.length + 60;
        $('#top-ctags-inner' + (index + 1)).css('height', chartHeight + 'px');
        $('#cblock' + (index + 1)).css('height', chartHeight + 20 + 'px');
        $(function() {
            if ($('#top-ctags-inner' + (index + 1)).length == 0)
                return;
            $('#top-ctags-inner' + (index + 1)).parents('.metrics-block').addClass('loaded');
            $('#top-ctags-inner' + (index + 1)).highcharts({
                chart: {
                    type: 'bar'
                },
                title: {
                    text: ''
                },
                xAxis: {
                    categories: tname,
                    tickPositions: tickPositions,
                    title: {
                        text: null
                    }
                },
                yAxis: {
                    min: 0,
                    minTickInterval: 1,
                    gridLineWidth: 0,
                    title: {
                        text: null,
                        align: 'high'
                    },
                    labels: {
                        overflow: 'justify',
                        enabled: false
                    }
                },
                tooltip: {
                    enabled: true,
                },
                plotOptions: {
                    bar: {
                        dataLabels: {
                            enabled: false
                        }
                    },
                    series: {
                        stacking: 'normal',
                        pointWidth: 15,
                        pointPadding: 1
                    }
                },
                legend: {
                    enabled: true,
                    reversed: true,
                    borderWidth: 0
                },
                credits: {
                    enabled: false
                },
                series: [{
                        name: 'Negative',
                        data: neg,
                        color: "#c0504d",
                        events: {
                            click: function(e) {
                                var category = e.point.category;
                                var group = tagComparisonGroups[category];
                                var tagid = tagComparisonData[group][category]['id'];
                                $('#tag-filter-widget>div>a').attr('data-value', tagid);
                                $('#selected-tag').text(category);
                                $('#tag-filter-widget>div').addClass('selected');
                                $('.radio-options-sentiment>a').last().addClass('selected');
                                $('#mentions-link-widget>a').click();
                            }
                        },
                        index: 0
                    }, {
                        name: 'Neutral',
                        data: neu,
                        color: "#9bbb59",
                        events: {
                            click: function(e) {
                                var category = e.point.category;
                                var group = tagComparisonGroups[category];
                                var tagid = tagComparisonData[group][category]['id'];
                                $('#tag-filter-widget>div>a').attr('data-value', tagid);
                                $('#selected-tag').text(category);
                                $('#tag-filter-widget>div').addClass('selected');
                                $('.radio-options-sentiment>a').last().prev().addClass('selected');
                                $('#mentions-link-widget>a').click();
                            }
                        },
                        visible: false,
                        index: 0
                    }, {
                        name: 'Positive',
                        data: pos,
                        color: "#4f81bd",
                        events: {
                            click: function(e) {
                                var category = e.point.category;
                                var group = tagComparisonGroups[category];
                                var tagid = tagComparisonData[group][category]['id'];
                                $('#tag-filter-widget>div>a').attr('data-value', tagid);
                                $('#selected-tag').text(category);
                                $('#tag-filter-widget>div').addClass('selected');
                                $('.radio-options-sentiment>a').first().addClass('selected');
                                $('#mentions-link-widget>a').click();
                            }
                        },
                        index: 1
                    }]
            });
        });
        index++;
    }
}

function loadSentimentByPlatforms() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    $('#sentiment_platforms-inner').parents('.metrics-block').removeClass('loaded');
    var streamId = window.location.href.split('#')[1].split('/')[1];
    var pl = new SOAPClientParameters();
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = $('#language-filter-widget a').first().attr('data-value');
    tags = $('#tag-filter-widget a').first().attr('data-value');
    sentiment = $('.radio-options-sentiment .selected').attr('data-value');
    type = $('#platform-filter-widget').find('a').attr('data-value');
    source = $('#source-filter-widget a').first().attr('data-value');
    var pl = new SOAPClientParameters();
    var filter = {};
    filter.streamId = streamId;
    filter.dateFrom = dateFrom;
    filter.dateTo = dateTo;
    filter.language = language;
    filter.tags = tags;
    filter.sentiment = sentiment;
    filter.type = type;
    filter.source = source;
    curRequests.push($.get('/ws/sentimentbyplatform/' + streamId + '/' + JSON.stringify(filter), function(r) {
        if (r !== 'null') {
            var data = JSON.parse(r);
            var pos = [];
            var neg = [];
            var neu = [];
            var categories = [];
            var tickPositions = [];
            var i = 0;
            for (var key in data) {
                categories.push(key);
                pos.push(data[key][1]);
                neu.push(data[key][0]);
                neg.push(data[key][ -1]);
                tickPositions.push(i);
                i++;
            }
            var chartHeight = 20 * categories.length + 60;
            $('#sentiment_platforms-inner').css('height', chartHeight + 'px');
            $('#sentiment_platforms-inner').parents('.metrics-block').css('height', chartHeight + 20 + 'px');
            $(function() {
                if ($('#sentiment_platforms-inner').length === 0)
                    return;
                $('#sentiment_platforms-inner').parents('.metrics-block').addClass('loaded');
                $('#sentiment_platforms-inner').highcharts({
                    chart: {
                        type: 'bar'
                    },
                    title: {
                        text: ''
                    },
                    xAxis: {
                        categories: categories,
                        tickPositions: tickPositions,
                        title: {
                            text: null
                        }
                    },
                    yAxis: {
                        min: 0,
                        minTickInterval: 1,
                        gridLineWidth: 0,
                        title: {
                            text: null,
                            align: 'high'
                        },
                        labels: {
                            overflow: 'justify',
                            enabled: false
                        }
                    },
                    tooltip: {
                        enabled: true,
                    },
                    plotOptions: {
                        bar: {
                            dataLabels: {
                                enabled: false
                            }
                        },
                        series: {
                            stacking: 'normal',
                            pointWidth: 15,
                            pointPadding: 1
                        }
                    },
                    legend: {
                        enabled: true,
                        reversed: true,
                        borderWidth: 0
                    },
                    credits: {
                        enabled: false
                    },
                    series: [{
                            name: 'Negative',
                            data: neg,
                            color: "#c0504d",
                            events: {
                                click: function(e) {
                                    var category = e.point.category;
                                    var tagid = data[category]['id'];
                                    $('#platform-filter-widget>div>a').attr('data-value', tagid);
                                    $('#platform-filter-widget .button-text').text(category);
                                    $('#platform-filter-widget>div').addClass('selected');
                                    $('.radio-options-sentiment>a').last().addClass('selected');
                                    $('#mentions-link-widget>a').click();
                                }
                            },
                            index: 0
                        }, {
                            name: 'Neutral',
                            data: neu,
                            color: "#9bbb59",
                            events: {
                                click: function(e) {
                                    var category = e.point.category;
                                    var tagid = data[category]['id'];
                                    $('#platform-filter-widget>div>a').attr('data-value', tagid);
                                    $('#platform-filter-widget .button-text').text(category);
                                    $('#platform-filter-widget>div').addClass('selected');
                                    $('.radio-options-sentiment>a').first().next().addClass('selected');
                                    $('#mentions-link-widget>a').click();
                                }
                            },
                            index: 0
                        }, {
                            name: 'Positive',
                            data: pos,
                            color: "#4f81bd",
                            events: {
                                click: function(e) {
                                    var category = e.point.category;
                                    var tagid = data[category]['id'];
                                    $('#platform-filter-widget>div>a').attr('data-value', tagid);
                                    $('#platform-filter-widget .button-text').text(category);
                                    $('#platform-filter-widget>div').addClass('selected');
                                    $('.radio-options-sentiment>a').first().addClass('selected');
                                    $('#mentions-link-widget>a').click();
                                }
                            },
                            index: 1
                        }]
                });
            });
        }
    }));
}

var sentimentBySource = {};
function loadSentimentBySources() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    $('#sentiment_sources-inner').parents('.metrics-block').removeClass('loaded');
    var streamId = window.location.href.split('#')[1].split('/')[1];
    var pl = new SOAPClientParameters();
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() !== 'metrics')
        return;
    dateFrom = $('#selected_date').attr('datefrom');
    dateTo = $('#selected_date').attr('dateto');
    language = $('#language-filter-widget a').first().attr('data-value');
    tags = $('#tag-filter-widget a').first().attr('data-value');
    sentiment = $('.radio-options-sentiment .selected').attr('data-value');
    type = $('#platform-filter-widget').find('a').attr('data-value');
    source = $('#source-filter-widget a').first().attr('data-value');
    if (count(sentimentBySource) === 0) {
        var filter = {};
        filter.streamId = streamId;
        filter.dateFrom = dateFrom;
        filter.dateTo = dateTo;
        filter.language = language;
        filter.tags = tags;
        filter.sentiment = sentiment;
        filter.type = type;
        filter.source = source;
        curRequests.push($.get('/ws/sentimentbysource/' + streamId + '/' + JSON.stringify(filter), function(r) {
            sentimentBySource = JSON.parse(r);
            renderSentimentBySources();
        }));
    }
    else {
        renderSentimentBySources();
    }
}

function renderSentimentBySources() {
    var pos = [];
    var neg = [];
    var neu = [];
    var categories = [];
    var tickPositions = [];
    var i = 0;
    for (var key in sentimentBySource) {
        categories.push(key);
        pos.push(sentimentBySource[key][1]);
        neu.push(sentimentBySource[key][0]);
        neg.push(sentimentBySource[key][ -1]);
        tickPositions.push(i);
        i++;
        if (i === parseInt($('.sentiment-source-filter .selected').text()))
            break;
    }
    var chartHeight = 20 * categories.length + 60;
    $('#sentiment_sources-inner').css('height', chartHeight + 'px');
    $('#sentiment_sources-inner').parents('.metrics-block').css('height', chartHeight + 20 + 'px');
    $(function() {
        if ($('#sentiment_sources-inner').length === 0)
            return;
        $('#sentiment_sources-inner').parents('.metrics-block').addClass('loaded');
        $('#sentiment_sources-inner').highcharts({
            chart: {
                type: 'bar'
            },
            title: {
                text: ''
            },
            xAxis: {
                categories: categories,
                tickPositions: tickPositions,
                title: {
                    text: null
                }
            },
            yAxis: {
                min: 0,
                minTickInterval: 1,
                gridLineWidth: 0,
                title: {
                    text: null,
                    align: 'high'
                },
                labels: {
                    overflow: 'justify',
                    enabled: false
                }
            },
            tooltip: {
                enabled: true,
            },
            plotOptions: {
                bar: {
                    dataLabels: {
                        enabled: false
                    }
                },
                series: {
                    stacking: 'normal',
                    pointWidth: 15,
                    pointPadding: 1
                }
            },
            legend: {
                enabled: true,
                reversed: true,
                borderWidth: 0
            },
            credits: {
                enabled: false
            },
            series: [{
                    name: 'Negative',
                    data: neg,
                    color: "#c0504d",
                    events: {
                        click: function(e) {
                            var category = e.point.category;
                            $('#source-filter-widget>div>a').attr('data-value', category);
                            $('#source-filter-widget .button-text').text(category);
                            $('#source-filter-widget>div').addClass('selected');
                            $('.radio-options-sentiment>a').last().addClass('selected');
                            $('#mentions-link-widget>a').click();
                        }
                    },
                    index: 0
                }, {
                    name: 'Neutral',
                    data: neu,
                    color: "#9bbb59",
                    events: {
                        click: function(e) {
                            var category = e.point.category;
                            $('#source-filter-widget>div>a').attr('data-value', category);
                            $('#source-filter-widget .button-text').text(category);
                            $('#source-filter-widget>div').addClass('selected');
                            $('.radio-options-sentiment>a').first().next().addClass('selected');
                            $('#mentions-link-widget>a').click();
                        }
                    },
                    index: 0
                }, {
                    name: 'Positive',
                    data: pos,
                    color: "#4f81bd",
                    events: {
                        click: function(e) {
                            var category = e.point.category;
                            $('#source-filter-widget>div>a').attr('data-value', category);
                            $('#source-filter-widget .button-text').text(category);
                            $('#source-filter-widget>div').addClass('selected');
                            $('.radio-options-sentiment>a').first().addClass('selected');
                            $('#mentions-link-widget>a').click();
                        }
                    },
                    index: 1
                }]
        });
    });
}

$(document).on('click', '.sentiment-source-filter li:not(.selected)', function() {
    var selected = $('.sentiment-source-filter .selected');
    selected.removeClass('selected');
    selected.addClass('not_selected');
    $(this).removeClass('not_selected');
    $(this).addClass('selected');
    loadSentimentBySources();
});
function loadMetrics() {
    if (window.location.href.split('#')[1].split('/')[0].toLowerCase() === 'metrics') {
        var req = curRequests.pop();
        while (req !== undefined) {
            req.abort();
            req = curRequests.pop();
        }
        metricsProcessing = true;
        clearInterval(timer);
        chartId = 0;
        timer = setInterval(function(ev) {
            switch (chartId) {
                case 0:
                    loadTrendLine();
                    chartId++;
                    break;
                case 1:
                    loadTopSocialPlatforms();
                    chartId++;
                    clearInterval(timer);
                    chartId = 0;
                    break;
                case 2:
                    loadSentimentData();
                    chartId++;
                    break;
                case 3:
                    loadTagMetric();
                    chartId++;
                    break;
                case 4:
                    loadTagsComparison();
                    chartId++;
                    break;
                case 5:
                    loadSentimentByPlatforms();
                    chartId++
                    break;
                case 6:
                    sentimentBySource = {};
                    loadSentimentBySources();
                    clearInterval(timer);
                    chartId = 0;
            }
        }, 500);
    }
    else {
        clearInterval(timer);
    }
}


function getTrueDate(date) {
    var day = String("0" + date.getDate()).slice(-2);
    var month = String("0" + (date.getMonth() + 1)).slice(-2);
    var year = date.getFullYear();
    return day + '-' + month + '-' + year;
}

function getDisplayDate(date) {
    var day = String("0" + date.getDate()).slice(-2);
    var month = parseMonth(date.getMonth());
    return month + ' ' + day;
}


function parseMonth(month) {
    switch (month) {
        case 0:
            return "Jan";
        case 1:
            return "Feb";
        case 2:
            return "Mar";
        case 3:
            return "Apr";
        case 4:
            return "May";
        case 5:
            return "Jun";
        case 6:
            return "Jul";
        case 7:
            return "Aug";
        case 8:
            return "Sep";
        case 9:
            return "Oct";
        case 10:
            return "Nov";
        case 11:
            return "Dec";
    }
}

$(document).on('click', '.social-platform .widget-item_count>div', function(e) {
    var smtArray = ["forum", "news", "blog", "facebook", "twitter", "youtube", "classifieds", "google plus", "retailers"];
    var text = $(this).find('.text').html();
    var smtId = smtArray.indexOf(text) + 1;
    $('#platform-filter-widget a').first().attr('data-value', smtId);
    $('#platform-filter-widget a span').first().html(text);
    $('#platform-filter-widget .filter-button').addClass('selected');
    $('.url-widget-link').first().click();
});
function getSMTName(type) {
    switch (type) {
        case 1:
            return "Forum";
        case 2:
            return "News";
        case 3:
            return "Blog";
        case 4:
            return "Facebook";
        case 5:
            return "Twitter";
        case 6:
            return "Youtube";
        case 7:
            return "Classifieds";
        case 8:
            return "Google Plus";
        case 9:
            return "Retailers";
    }
}